package com.hzw.saas.service.project.flow.service;

import com.hzw.saas.common.config.model.BaseLogicModel;
import com.hzw.saas.common.config.model.BaseModel;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.flow.exception.FlowServiceHandleException;
import com.hzw.saas.common.flow.pojo.model.FlowInstance;
import com.hzw.saas.common.flow.pojo.model.FlowProcessRecord;
import com.hzw.saas.common.flow.service.FlowActionHandle;
import com.hzw.saas.common.util.AccountValidatorUtil;
import com.hzw.saas.common.util.ObjFieldUtil;
import com.hzw.saas.service.project.constants.ProjectConsts;
import com.hzw.saas.service.project.model.ProjectApply;
import com.hzw.saas.service.project.service.IProjectApplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author zzl
 * @since 08/13/2021
 */
@Service(ProjectConsts.PROJECT_APPLY_SERVICE_SUBMIT)
@Slf4j
public class ProjectApplyServiceSubmitImpl implements FlowActionHandle {

    @Resource
    private IProjectApplyService projectApplyService;

    @Override
    public void handle(FlowInstance flowInstance, FlowProcessRecord flowProcessRecord) throws FlowServiceHandleException {
        ProjectApply projectApply = projectApplyService.lambdaQuery()
            .eq(ProjectApply::getFlowInstanceId, flowProcessRecord.getFlowInstanceId())
            .last("LIMIT 1").one();
        AssertUtil.assertThrow("找不到项目申请信息", Objects.isNull(projectApply));
        // 电话和邮箱验证
        boolean emailValid = AccountValidatorUtil.isEmail(projectApply.getEmail());
        AssertUtil.assertThrow("邮箱格式错误", !emailValid);
        boolean mobileValid = AccountValidatorUtil.isMobile(projectApply.getPhone());
        boolean landlineValid = AccountValidatorUtil.isLandline(projectApply.getPhone());
        AssertUtil.assertThrow("电话格式错误", !mobileValid && !landlineValid);
        // 其他参数验证
        boolean hasBlankFiled = ObjFieldUtil.hasBlankFiled(projectApply,
            ProjectApply::getAcceptanceInstruction,
            BaseLogicModel::getIsDelete,
            BaseModel::getCreatorId,
            BaseModel::getEditorId,
            BaseModel::getCreateTime,
            BaseModel::getUpdateTime);
        AssertUtil.assertThrow("信息填写不完整", hasBlankFiled);
        boolean notMatchLimit = projectApply.getResearchPlan().length() < 1000;
        AssertUtil.assertThrow("信息填写不完整", notMatchLimit);
    }

}
